package com.yiyuan.app.filter;

import com.alibaba.fastjson.JSON;
import com.guaike.core.entity.constant.HttpHeaderConstant;
import com.guaike.core.entity.exception.ApiException;
import com.guaike.core.web.helper.RequestSignHelper;
import com.yiyuan.app.dao.OAppVersionDAO;
import com.yiyuan.app.entity.po.OAppVersionPO;
import com.yiyuan.app.entity.result.VersionVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class AppUpdateFilter implements Filter {


    private static final String[] WHITE_URLS = new String[]{"/doc.html", "/webjars/bycdao-ui", "/swagger-resources", "/v2/api-docs"};

    private OAppVersionDAO oAppVersionDAO;

    public void setoAppVersionDAO(OAppVersionDAO oAppVersionDAO) {
        this.oAppVersionDAO = oAppVersionDAO;
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURI();
        String[] var6 = WHITE_URLS;
        int var7 = var6.length;
        String uri;
        for (int var8 = 0; var8 < var7; ++var8) {
            uri = var6[var8];
            if (url.contains(uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        if (RequestSignHelper.isNoSign(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (url.equalsIgnoreCase("/login/checkAppUpdate")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        VersionVO result = new VersionVO();
        String clientId = request.getHeader(HttpHeaderConstant.HEADER_NAME_CID);
        String clientVersion = request.getHeader(HttpHeaderConstant.HEADER_NAME_CV);
        OAppVersionPO latestVersion = oAppVersionDAO.findLatestVersion(clientId);
        if (Objects.nonNull(latestVersion) && clientVersion.compareTo(latestVersion.getVersionNo()) < 0) {
            OAppVersionPO versionPO = oAppVersionDAO.findLatestUpdateVersion(clientId);
            if (Objects.nonNull(versionPO) && clientVersion.compareTo(versionPO.getVersionNo()) < 0) {
                result.setIsUpdate(Boolean.TRUE);
                result.setVersion(latestVersion.getVersionNo());
                result.setDownLoadUrl(latestVersion.getUrl());
                throw new ApiException("100", JSON.toJSONString(result));
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
